<?php
declare (strict_types=1);

namespace app\exam\logic;

use app\common\exception\LogicException;
use app\exam\model\PersonalRecord as PersonalRecordModel;
use think\Model;

class PersonalRecord extends PersonalRecordModel
{

    /**
     * updatePersonalRecord
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 24/06/07
     *
     * @param int $topCate
     * @param int $topicCount
     * @param int $rightCount
     * @param int $type
     */
    public function updatePersonalRecord(int $topCate, int $topicCount, int $rightCount, int $type)
    {
        $mid       = request()->mid;
        $perRecord = $this->where('category', $topCate)->where('user', $mid)->findOrEmpty();
        if ($perRecord->isEmpty()) {
            // 添加记录
            $add = $this::create([
                // 'type'     => $type,
                'category' => $topCate,
                'user'     => $mid,
                'today'    => $topicCount,
                'right'    => $rightCount,
                'total'    => $topicCount,
                'rate'     => bcdiv(strval($rightCount * 100), strval($topicCount))
            ]);
            if ($add->isEmpty()) throw new LogicException('做题统计失败');
        } else {
            // 更新记录
            $today = strtotime('today') <= $perRecord->update_time;
            if ($today) {
                $perRecord->today += $topicCount;
            } else {
                $perRecord->today = $topicCount;
            }
            $perRecord->right += $rightCount;
            $perRecord->total += $topicCount;
            $perRecord->rate  = bcdiv(strval($perRecord->right * 100), strval($perRecord->total));
            if (!$perRecord->save()) throw new LogicException('做题统计失败');
        }
    }

    /**
     * getPersonalRecord
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 24/06/07
     *
     * @param int $cate
     * @return PersonalRecord|array|Model
     */
    public function getPersonalRecord(int $cate)
    {
        $data = $this->field('today,total,rate,update_time')->where('category', $cate)->where('user', request()->mid)->findOrEmpty();
        if ($data->isEmpty()) {
            $data->today = 0;
            $data->total = 0;
            $data->rate  = 0;
        } else if ($data->update_time < strtotime('today')) {
            $data->today = 0;
        }
        return $data;
    }
}
